package com.hanwei.uap.acceptors.sstn.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 使用netty分隔符解码器
 *
 * @author zhaoam
 * @create 2017-08-07 18:58
 **/
@Component
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    private int IDEL_TIME_OUT = 1200;
    @Value("${uap.server.timeout}")
    private int READ_IDEL_TIME_OUT = 1200;
    private int WRITE_IDEL_TIME_OUT = 1200;
    @Autowired
    @Qualifier("nettyServerHandler")
    private ChannelHandler channelHandler;
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{(byte)0x0d});
        pipeline.addLast("idleStateHandler", new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, IDEL_TIME_OUT));
        pipeline.addLast(new DelimiterBasedFrameDecoder(2048,false,delimiter));
        pipeline.addLast(channelHandler);
    }
}
